﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Mrc.ConfigMaster.Models;
using Mrc.Config;
using System.Text;
using Mrc.Common;
using Mrc.Common.Enum;
using Mrc.SqlSurging;
using Mrc.Domain.Module.Auth;
using Mrc.RabbitMQ;
using Mrc.Domain.Module.ConfigCenter;
using Mrc.Domain.Entitity;
using Mrc.Config.Messages;
using Mrc.Application;
using Mrc.Domain.Dto;
using Mrc.Common.Helpers;

namespace Mrc.ConfigMaster.Controllers
{
   
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IRabbitmqPublish _rabbitmqPublish;
        private readonly IJsonConfigFileProvider _jsonConfigFileProvider;
        private readonly ISqlSurgarClientService _sqlSurgarClientService;
        private readonly ISysConfigService _sysConfigService;
        public HomeController(
            ILogger<HomeController> logger,
            IRabbitmqPublish rabbitmqPublish,
            IJsonConfigFileProvider jsonConfigFileProvider,
            ISqlSurgarClientService sqlSurgarClientService,
            ISysConfigService sysConfigService
            )
        {
            _jsonConfigFileProvider = jsonConfigFileProvider;
            _rabbitmqPublish = rabbitmqPublish;
            _logger = logger;
            _sqlSurgarClientService = sqlSurgarClientService;
            _sysConfigService = sysConfigService;
        }
        [UserLogin]
        public IActionResult Index()
        {
            return View();
        }
        [UserLogin]
        public IActionResult Configs()
        {
            return View();
        }
        [UserLogin]
        public IActionResult AddView()
        {
            return View();
        }

        /// <summary>
        /// 添加配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [UserLogin]
        public async Task<ActionResult> Add(SysConfig model)
        {
            var result = await new SysConfigManager().Add(new SysConfig
            {
                Content = model.Content,
                Env = model.Env,
                FileName = model.FileName,
                ItemName = model.ItemName,
                KeyName = "",
                Version = model.Version
            });
            _rabbitmqPublish.SendConfigMsg(new ConfigMessages
            {
                MsgType = NoticeMsgTypeEnum.ConfigMsg,
                Values = result.ToDictionary(x=>x.Key,x=>(object)x.Value)
            });
            return Json(new AjaxResult(ResultStatus.OK, "添加成功"));
        }
        [UserLogin]
        public JsonResult GetConfigsIteams(int pageNumber, int pageSize)
        {
            var service = new SysConfigService();
            var datas = service.Db.Queryable<SysConfig>().ToLayuiTable(pageNumber, pageSize);            
            return Json(datas);
        }

        /// <summary>
        /// 获取初始配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonResult GetInitConfigs(string ItemName, int Env)
        {
            var service = new SysConfigService();
            Dictionary<string, object> Values = new Dictionary<string, object>();
            var datas = service.Db.Queryable<SysConfig>().ToList();
            foreach (var item in datas)
            {
                if (!Values.ContainsKey(item.KeyName)) Values.Add(item.KeyName, item.Content);
            }
            return Json(new Config.Messages.ConfigMessages
            {
                ItemName = ItemName,
                MsgType = Config.Messages.NoticeMsgTypeEnum.ConfigMsg,
                Values = Values
            });
        }

        public JsonResult Send()
        {
            var service = new SysConfigService();
            var datas = service.Db.Queryable<SysConfig>().ToList();
            Dictionary<string, object> Values = new Dictionary<string, object>();
            foreach (var item in datas)
            {
                if (!Values.ContainsKey(item.KeyName)) Values.Add(item.KeyName, item.Content);
            }
            _rabbitmqPublish.SendConfigMsg(new ConfigMessages
            {
                MsgType =  NoticeMsgTypeEnum.ConfigMsg,
                Values = Values
            });
            return Json(new AjaxResult(ResultStatus.OK, "成功"));
        }
        public JsonResult Send2()
        {
            var service = new SysConfigService();
            var datas = service.Db.Queryable<SysConfig>().ToList();
            Dictionary<string, object> Values = new Dictionary<string, object>();

            _rabbitmqPublish.SendConfigMsg(new ConfigMessages
            {
                MsgType = NoticeMsgTypeEnum.HealthCheckMsg,
                Values = Values
            });

            return Json(new AjaxResult(ResultStatus.OK, "成功"));
        }

        public JsonResult Test()
        {
            var stearm = _jsonConfigFileProvider.GetStream("hosting");
            var str = StreamHelpers.StreamToUTF8String(stearm);
            RsaEncryHelper.test();
            return Json(new AjaxResult(ResultStatus.OK, str));
        }

        public async Task<JsonResult> TestSqlSurgar()
        {
            var data = await Task.Run(() => _sqlSurgarClientService.Client("admin").Queryable<SysConfig>().ToList());
            return Json(new AjaxResult<List<SysConfig>>(ResultStatus.OK, data));
        }
        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }


        public JsonResult Money()
        {
            var info = new Common.SystemInfo.MachineInfoManager();
            info.Init();
            info._machineInfo.AvailableMemory = info._machineInfo.AvailableMemory / 1024 / 1024;
            info._machineInfo.Memory = info._machineInfo.Memory / 1024 / 1024;
            info.FreshCpuAndMoney();
            return Json(info._machineInfo);
        }
    }
}
